#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
MY_FILE* my_fopen(const char *path, const char *mode)
{
  int flag=0;
  if(strcmp(mode,"w")==0)
  {
   flag|=(O_WRONLY|O_TRUNC|O_CREAT);
  }
  if(strcmp(mode,"r")==0)
  {
flag|=O_RDONLY;
  }
  if(strcmp(mode,"a")==0)
  {
    flag|=(O_WRONLY|O_APPEND|O_CREAT);
  }
  mode_t m=0666;
  int my_fd=0;
  if(flag&O_CREAT) 
  {
    my_fd=open(path,flag,m);
  }
  else
  {
    my_fd=open(path,flag);
  }
MY_FILE* ret=(MY_FILE*)malloc(sizeof(MY_FILE));
if(ret==NULL)
{
  close(my_fd);
return NULL;
}
ret->fd=my_fd;
ret->flags=0;
ret->flags|=BUFF_LINE;
ret->current=0;
memset(ret->buffer_area,'\0',MAX);
return ret;
}




void my_fflush(MY_FILE* fp)
{
  assert(fp);
write(fp->fd,fp->buffer_area,fp->current);
fp->current=0;
}




size_t my_fwrite(const void *ptr, size_t size, size_t nmemb,MY_FILE *stream)
{
if(stream->current==MAX)
{
  my_fflush(stream);
}
size_t ret=0;
size_t user_size=size*nmemb;
size_t my_size=MAX-stream->current;
if(my_size>=user_size)
{
memcpy(stream->buffer_area+stream->current,ptr,user_size);
stream->current+=user_size;
ret=user_size;
}
else 
{
memcpy(stream->buffer_area+stream->current,ptr,my_size);
stream->current+=my_size;
ret=my_size;
}

if(stream->flags&BUFF_ALL)
{
if(stream->current==MAX)
{
 my_fflush(stream);
}
}
else if(stream->flags&BUFF_LINE)
{
  if(stream->buffer_area[stream->current-1]=='\n')
  {
    my_fflush(stream);
  }
}
else
{
my_fflush(stream);

}

return ret;





}


 int my_fclose(MY_FILE* fp)
{
  assert(fp);
  if(fp->current>0)
  {
my_fflush(fp);
  }
close(fp->fd);
free(fp);
fp=NULL;
}


